package com.cade.agriculturemall.view.personalCenter.ordersManage;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseAdapter;
import com.cade.agriculturemall.base.BaseFragment;
import com.cade.agriculturemall.model.OrderEntity;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.utils.RefreshLayout;
import com.cade.agriculturemall.view.personalCenter.ordersManage.OrderItems.OrderActivity;
import com.cade.agriculturemall.view.refresh.OnRefreshListener;
import com.cade.agriculturemall.view.shoppingCar.ShopCarsExpandableListAdapter;
import com.cade.agriculturemall.view.shoppingCar.settlement.SettlementViewModel;
import com.cade.agriculturemall.widget.EmptyLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MerchandiseListBaseFragment extends BaseFragment<MyOrdersContract.IPresenter> implements MyOrdersContract.IView, OnRefreshListener, MerchandiseListAdapter.MyClickListener {

    RecyclerView swipeTarget;//
    MerchandiseListAdapter adapter;
    public int type;
    private boolean isPrepared = false;
    private RefreshLayout refreshLayout;
    private EmptyLayout emptyLayout;
    private OrderEntity seleteData = new OrderEntity();


    public void initView(View view) {
        /*
         * 获取页签类型  0全部 1待发货 2待收货 3已完成
         */
        Bundle args = getArguments();
        if (args != null) {
            String typeTemp = args.getString("type");
            type = Integer.valueOf(typeTemp);
        }
        adapter = new MerchandiseListAdapter(getActivity(), this);
        adapter.notifyDataSetChanged();
        swipeTarget.setAdapter(adapter);
        swipeTarget.setHasFixedSize(true);
        swipeTarget.setLayoutManager(new LinearLayoutManager(getActivity()));
        isPrepared = true;

/**adapter itemOnClick 点击跳转至订单详情页面
 */
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                List<SettlementViewModel> models = adapter.getModels();
                type = models.get(position).getType();
                OrderEntity entity;
                Intent intent = new Intent(getActivity(), OrderActivity.class);
                switch (type) {
                    case SettlementViewModel.TYPE_ORDER_TIME:
                        entity = (OrderEntity) models.get(position).getObject();
                        intent.putExtra("orderNo", entity.getOrderId());
                        break;
                    case SettlementViewModel.TYPE_SJ:
                        entity = (OrderEntity) adapter.getModels().get(position - 1).getObject();
                        intent.putExtra("orderNo", entity.getOrderId());
                        break;
                    case SettlementViewModel.TYPE_CP:
                        int i;
                        for (i = 1; i <= position; i++) {
                            if (models.get(position - i).getType() == SettlementViewModel.TYPE_ORDER_TIME) {
                                entity = (OrderEntity) adapter.getModels().get(position - i).getObject();
                                intent.putExtra("orderNo", entity.getOrderId());
                                break;
                            }
                        }
                        break;
                    case SettlementViewModel.TYPE_OPERATE_BUTTON:
                        entity = (OrderEntity) adapter.getModels().get(position).getObject();
                        intent.putExtra("orderNo", entity.getOrderId());
                        break;
                }
                startActivity(intent);
            }
        });
    }

    public void doViewRefresh(OrderEntity orderEntity) {
        hashMap.remove(orderEntity);
        onDownloadEntity(hashMap);
//        adapter.notifyDataSetChanged();
    }

    @Override
    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("删除后订单不可恢复，是否继续删除订单？").setTitle("确认删除订单？").setPositiveButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mPresenter.goodsDelete(seleteData);
            }
        });
    }

    @Override
    public void deleteSuccess() {
        Toast.makeText(getActivity(), "订单删除成功", Toast.LENGTH_SHORT);

    }

    @Override
    public void deleteFail() {
        Toast.makeText(getActivity(), "订单不可删除", Toast.LENGTH_SHORT);
    }

    //
//    //统一的Fragment构建方法
    public static MerchandiseListBaseFragment newInstance(int flag) {
        Bundle args = new Bundle();
        //type代表页签，0：全部订单 1：待发货 2：待收货 3：已完成 4:未付款
        args.putString("type", String.valueOf(flag));
        MerchandiseListBaseFragment fragment = new MerchandiseListBaseFragment();
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 获取订单类型
     *
     * @return
     */
    public int getType() {
        return type;
    }

    @Override
    public int setupLayout() {
        return R.layout.fragment_merchandise_list;
    }

    @Override
    public void setupView() {
        emptyLayout = (EmptyLayout) getView().findViewById(R.id.fragment_merchandise_emptylayout);
        swipeTarget = (RecyclerView) getView().findViewById(R.id.swipe_target);
        refreshLayout = (RefreshLayout) getView().findViewById(R.id.fragment_merchandise_refresh);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setLoadMoreEnable(false);
    }

    @Override
    public void setupEvent() {
        initView(getView());
    }

    @Override
    public void setupData() {
    }

    @Override
    public MyOrdersContract.IPresenter setupPresenter() {
        return new MyOrdersPresenter(this);
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isPrepared) {
            //相当于Fragment的onResume方法
//            mPresenter.downLoadAllEntity(type);
//            fresh();
        } else {
            //相当于Fragment的onPause
        }

    }


    HashMap<OrderEntity, List<ShoppingCarsEntity>> hashMap = new HashMap();

    @Override
    public void onDownloadEntity(HashMap<OrderEntity, List<ShoppingCarsEntity>> hashMap) {
        this.hashMap = hashMap;
        List<SettlementViewModel> models = new ArrayList<>();
        if (hashMap.size() != 0) {
            for (OrderEntity orderEntity : hashMap.keySet()) {
                models.add(new SettlementViewModel(SettlementViewModel.TYPE_ORDER_TIME, orderEntity));
                models.add(new SettlementViewModel(SettlementViewModel.TYPE_SJ, hashMap.get(orderEntity).get(0).getShoper()));
                for (ShoppingCarsEntity entity : hashMap.get(orderEntity)) {
                    SettlementViewModel viewModel = new SettlementViewModel(SettlementViewModel.TYPE_CP, entity);
                    models.add(viewModel);
                }
                models.add(new SettlementViewModel(SettlementViewModel.TYPE_OPERATE_BUTTON, orderEntity));
            }
        }
        adapter.setModels(models);
        if (models.size() != 0) {
            emptyLayout.reset();
            adapter.setModels(models);
            adapter.notifyDataSetChanged();
        } else {
            emptyLayout.empty();
        }
        refreshLayout.endRefreshing();
    }

    @Override
    public void onStartRefresh() {
        mPresenter.downLoadAllEntity(type);
    }

    @Override
    public void goPayClick(String orderObjectId) {
        Intent intent = new Intent(getActivity(), OrderActivity.class);
        intent.putExtra("orderNo", orderObjectId);
//        intent.putExtra("orderId", orderObjectId);
        startActivity(intent);
    }
}
